#!/bin/sh

# print vpnc version from file VERSION, appending the string printed
# by svnversion(1) if appropriate

in_git_repository ()
{
	git rev-parse --is-inside-work-tree > /dev/null 2>&1
	return $?
}

git_svn_version ()
{
	# search for svn-remote defined in git configuration
	svn_url_pattern=""
	while read key value; do
		svn_url_pattern="${svn_url_pattern}\\|${value}"
	done << EOF
	$(git config --get-regexp '^svn-remote\..*\.url$' 2>/dev/null)
EOF

	# exit if no svn-remote defined
	if [ -z "${svn_url_pattern}" ]; then
		return
	fi

	# scan git-log for latest commit from any svn-remote above
	set -- $(git log --first-parent -1 \
		--grep="^git-svn-id: \(${svn_url_pattern#??}\)@" 2>/dev/null)

	# check commit hash is 40 hex digits
	svn_commit=$2
	if [ ${#svn_commit} -ne 40 -o -z "${svn_commit##*[!0-9a-f]*}" ]; then
		return
	fi

	# check svn version is numeric
	shift $(($# - 2))
	svn_ver=${1#*@}
	if [ -z "${svn_ver}" -o -z "${svn_ver##*[!0-9]*}" ]; then
		return
	fi

	if [ $(git rev-list HEAD...${svn_commit} | wc -l) -eq 0 ]; then
		if [ `git status -s | grep -vc '^??'` -eq 0 ]; then
			# no git commits and tree clean
			echo "${svn_ver}"
			return
		fi
	fi
	# there are local git commits after latest svn commit or tree is dirty
	echo "${svn_ver}M"
}


_version="`cat VERSION`"

if [ -d .svn ]; then
	if which svnversion > /dev/null; then
		_version="$_version-`svnversion`"
	else
		_version="$_version-`sed -n '/^dir$/{n;p;q;}' .svn/entries`"
	fi
elif which git > /dev/null && in_git_repository; then
	git_ext=$(git_svn_version)
	if [ -n "${git_ext}" ]; then
		_version="$_version-${git_ext}"
	fi
fi

echo "$_version"

exit 0
